package com.amt.iptvsetting.business.main;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.app.ActivityOptionsCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.callback.NavigationCallback;
import com.alibaba.android.arouter.launcher.ARouter;
import com.amt.iptvsetting.R;
import com.amt.iptvsetting.business.main.entity.MainListItemEntity;
import com.amt.iptvsetting.business.main.event.MainActivityEvent;
import com.app.common.CommonManagerKt;
import com.app.common.activity.BaseActivity;
import com.app.common.adapter.BaseRecyclerViewAdapter;
import com.app.common.utils.JsonUtilKt;
import com.app.dprocessone.ClientInterface;
import com.app.dprocessone.DaemonProcessOneAidl;
import com.app.dprocessone.service.DaemonProcessOneService;
import com.app.network.ApiManager;
import com.app.network.entity.Contributor;
import com.app.network.entity.NetWorkTestEntity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import dagger.android.AndroidInjection;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


/**
 * @创建人 周文东
 * @创建时间 2019/11/3
 * @描述
 */
public class MainActivity extends BaseActivity  {

    private static final String TAG = MainActivity.class.getSimpleName();

    @BindView(R.id.activity_main_list)
    RecyclerView activityMainList;

    private List<MainListItemEntity> data = new ArrayList<>();

    private MainListAdapter adapter;

    @Inject
    ApiManager apiManager;

    private DaemonProcessOneService service;

    private DaemonProcessOneAidl daemonProcessOneAidl;

    @Inject
    NetWorkTestEntity netWorkTestEntity;

    //需要申请的所有权限
    private String[] permissions = new String[]{Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO};
    private final int mRequestCode = 100;//权限请求码
    //装取未申请的权限
    private List<String>  mPermissionList = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AndroidInjection.inject(this);
        setContentView(R.layout.activity_main1);
        ButterKnife.bind(this);

        try {
            Log.i(TAG, "onCreate: netWorkTestEntity -> " + netWorkTestEntity);

            apiManager.contributors("square", "retrofit")
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<List<Contributor>>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            Log.i(TAG, "onSubscribe: ");
                        }

                        @Override
                        public void onNext(List<Contributor> contributors) {
                            Log.i(TAG, "onResponse: contributors -> " + contributors);
                        }

                        @Override
                        public void onError(Throwable e) {
                            Log.i(TAG, "onError: ");
                        }

                        @Override
                        public void onComplete() {
                            Log.i(TAG, "onComplete: ");
                        }
                    });

        } catch (Exception e) {
            Log.e(TAG, "onCreate: ", e);
            e.printStackTrace();
        }
        initPermission();
        initData();

        initAdapter();
    }

    /**
     *@描述 初始化权限，针对6.0以上系统的机子
     *@参数
     *@返回值  void
     *@创建人  zhouwd
     *@创建时间
     *@修改人和其它信息
     */
    private void initPermission() {
        mPermissionList.clear();//清空已经允许的没有通过的权限
        //逐个判断是否还有未通过的权限
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(this, permissions[i]) !=
                    PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);//添加还未授予的权限到mPermissionList中
            }
        }

        if (mPermissionList.size() > 0) {//有权限没有通过，需要申请
            //申请权限
            ActivityCompat.requestPermissions(this, permissions, mRequestCode);
        } else {
            //权限已经都通过了，可以将程序继续打开了
            //startApp();
        }
    }


    /**
     * 绑定
     */
    private void bind() {

        Intent intent = new Intent(this, DaemonProcessOneService.class);

        bindService(intent, serviceConnection, BIND_AUTO_CREATE);

    }

    /**
     * 取消绑定
     */
    private void unBind() {
        unbindService(serviceConnection);
    }

    private ClientInterface clientInterface = new ClientInterface() {
        @Override
        public String messageFromClient() throws RemoteException {

            return "messageFromClient";
        }

        @Override
        public IBinder asBinder() {

            return null;
        }
    };

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            daemonProcessOneAidl = DaemonProcessOneAidl.Stub.asInterface(service);

            try {

                daemonProcessOneAidl.registerClient(clientInterface);

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            daemonProcessOneAidl = null;
        }
    };


    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MainActivityEvent mainActivityEvent) {
        /* Do something */
        MainActivityEvent.EVENT event = mainActivityEvent.getEvent();
        String message = mainActivityEvent.getMessage();



    }

    /**
     * 初始化数据
     *
     * @author zhouwd
     */
    private void initData() {
        //
        //Single.
        Observable.create((ObservableOnSubscribe<List<MainListItemEntity>>) emitter -> {
            StringBuilder sb = new StringBuilder();
            InputStream is = null;
            BufferedReader br = null;
            try {
                is = getAssets().open("data/main_data.json");
                br = new BufferedReader(new InputStreamReader(new BufferedInputStream(is)));

                while (true) {

                    String data = br.readLine();

                    if (data != null) {
                        sb.append(data);
                    } else {
                        break;
                    }
                }

                List<MainListItemEntity> data = JsonUtilKt.Json2Array(sb.toString(), MainListItemEntity.class);

                emitter.onNext(data);
            } catch (Exception e) {
                emitter.onError(e);
                e.printStackTrace();
            } finally {
                if (is != null) {
                    is.close();
                }

                if (br != null) {
                    br.close();
                }

            }


        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<MainListItemEntity>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(List<MainListItemEntity> mainListItemEntities) {
                        Log.i(TAG, "onNext: mainListItemEntities -> " + mainListItemEntities);
                        data.addAll(mainListItemEntities);

                        if (adapter != null) {
                            adapter.notifyDataSetChanged();
                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });



    }

    /**
     * 初始化适配器
     *
     * @author zhouwd
     */
    private void initAdapter() {

        adapter = new MainListAdapter(data, this);
        activityMainList.setLayoutManager(new GridLayoutManager(this, 2));
        activityMainList.setAdapter(adapter);

    }

    class MainListAdapter extends BaseRecyclerViewAdapter<MainListItemEntity, MainListAdapter.ViewHolder> {

        private final String TAG = MainListAdapter.class.getSimpleName();



        public MainListAdapter(List<MainListItemEntity> data, Context context) {
            super(data, context);


        }


        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = getInflater().inflate(R.layout.activity_main_list_item, parent, false);

            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            MainListItemEntity mainListItemEntity = getData().get(position);
            try {

                String title = mainListItemEntity.getTitle();

                Log.i(TAG, "onBindViewHolder: title -> " + title);

                holder.activityMainListItemTitle.setText(title);

                final String router = mainListItemEntity.getRouter();

                Log.i(TAG, "onBindViewHolder: router -> " + router);

                holder.itemView.setOnClickListener(v -> {

                    // 转场动画(API16+)
                    ActivityOptionsCompat compat = ActivityOptionsCompat.
                            makeScaleUpAnimation(v, v.getWidth() / 2, v.getHeight() / 2, 0, 0);

                    Bundle bundle = new Bundle();
                    bundle.putChar("key", 'a');

                    ARouter.getInstance().build(router)
                            //.withString("key1", "value1")
                            .withOptionsCompat(compat)
                            .with(bundle)
                            .navigation(getContext(), new NavigationCallback() {
                                @Override
                                public void onFound(Postcard postcard) {
                                    Log.i(TAG, "onFound: ");

                                }

                                @Override
                                public void onLost(Postcard postcard) {
                                    Log.i(TAG, "onLost: ");

                                }

                                @Override
                                public void onArrival(Postcard postcard) {
                                    Log.i(TAG, "onArrival: ");

                                }

                                @Override
                                public void onInterrupt(Postcard postcard) {
                                    Log.i(TAG, "onInterrupt: ");
                                    Bundle resultBundle = postcard.getExtras();

                                    String result = resultBundle.getString("result");

                                    //EventBus.getDefault().post(new MainActivityEvent(MainActivityEvent.EVENT.TOAST, result));

                                    MainActivity.this.runOnUiThread(() -> CommonManagerKt.showLongToast("" + result));


                                    //Toast.makeText(getContext(), result, Toast.LENGTH_LONG).show();
                                    Log.i(TAG, "onInterrupt: result -> " + result);
                                }
                            });
                });

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        class ViewHolder extends RecyclerView.ViewHolder {

            @BindView(R.id.activity_main_list_item_title)
            TextView activityMainListItemTitle;

            ViewHolder(@NonNull View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);

            }
        }

    }

    /**
     * 5.请求权限后回调的方法
     * @param requestCode 是我们自己定义的权限请求码
     * @param permissions 是我们请求的权限名称数组
     * @param grantResults 是我们在弹出页面后是否允许权限的标识数组，数组的长度对应的是权限
     *                     名称数组的长度，数组的数据0表示允许权限，-1表示我们点击了禁止权限
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean hasPermissionDismiss = false;//有权限没有通过
        if (mRequestCode==requestCode){
            for (int i=0;i<grantResults.length;i++){
                if (grantResults[i]==-1){
                    hasPermissionDismiss=true;
                    break;
                }
            }
        }
        if (hasPermissionDismiss){//如果有没有被允许的权限
            //showPermissionDialog();
        }else {
            //权限已经都通过了，可以将程序继续打开了
            //startApp();
        }
    }


}
